package com.lxw.filesystem.service.impl;

import com.lxw.filesystem.dao.FileSystemDao;
import com.lxw.filesystem.service.IFileSystemService;
import com.lxw.filesystem.service.IOssService;
import com.lxw.framework.domain.filesystem.FileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileSystemServiceImpl implements IFileSystemService {

    @Autowired
    IOssService ossService;

    @Autowired
    FileSystemDao fileSystemDao;

    @Override
    public FileSystem upload(MultipartFile multipartFile, String filetag, String businesskey, String metadata) {
        //上传文件到远端
        String originalFilename = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String newName = uuid.replace("-","")+originalFilename.substring(originalFilename.lastIndexOf("."));

        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件上传
        String fileUrl = ossService.UploadFile(newName, inputStream);

        //文件保存
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileUrl);
        fileSystem.setFilePath(fileUrl);
        fileSystem.setFileName(originalFilename);
        fileSystem.setFiletag(filetag);
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFileType(multipartFile.getContentType());
        fileSystem.setFileSize(multipartFile.getSize());
        fileSystemDao.save(fileSystem);
        return fileSystem;
    }
}
